/**   
 *    
 * 项目名称：MedicalTeam   
 * 类名称：拦截器工具类  
 * 类描述：   激活码
 * 创建人：zhangl  
 * 创建时间：2016年9月2日 上午18:33:50
 * 修改人：zhangl   
 * 修改时间：2016年9月2日 上午18:33:50
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.common;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lst.model.MySession;

/**
 * 
 * @ClassName: HandlerInterceptor
 * @Description: 预处理
 * @author zhangl
 * @date 2016年9月2日 上午18:33:50
 * 
 */
public class SpringHandlerInterceptor extends HandlerInterceptorAdapter {

	protected static Logger logger = Logger.getLogger("log");

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		reqResLog(request, " preHandle start: ");
		
		MySession mySession = (MySession) request.getSession().getAttribute(CommonEnum.SESSION_KEY);
		
		String url = request.getRequestURI();
		
		if(url.indexOf("/doLogin") > -1 || url.indexOf("/shareContentController") > -1 || url.indexOf("/kungfuDownController") > -1 || url.indexOf("/clientGrowthController") > -1 || url.indexOf("/doRegister") > -1 || url.indexOf("/inviteController") > -1){//请求登录，获取验证码时直接跳过
			return true;
		}
		if (mySession == null || mySession.getMstUser() == null) { //未登录
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ //如果是ajax请求响应头会有，x-requested-with  
                response.setHeader("sessionstatus", "timeout");//在响应头设置session状态  
            }else{
                response.sendRedirect(request.getContextPath());
             //   return false;
            }  
            
        }
		
        return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		reqResLog(request, " postHandle start: ");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		reqResLog(request, " afterCompletion start: ");
	}

	private void reqResLog(HttpServletRequest request, String funString) {
		try {
			String reqUrlString = request.getRequestURI();
			Date startDate = new Date();

			logger.info(reqUrlString + funString + startDate);
		} catch (Exception e) {
			logger.error("afterCompletion error : ",e);
		}
		
	}

}
